package com.rpc.demo.tomcat;

import com.rpc.demo.pojo.Invocation;
import com.rpc.demo.pojo.URL;
import com.rpc.demo.registry.NativeRegistry;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class HttpServerHandler {
	/**
	 * 服务处理
	 * @param req
	 * @param resp
	 */
	public void handle(HttpServletRequest req, HttpServletResponse resp) {
		//服务请求的处理逻辑


		try {
			//1通过请求流获取请求服务的调用参数
			ServletInputStream inputStream = req.getInputStream();
			ObjectInputStream obj = new ObjectInputStream(inputStream);
			Invocation invocation = (Invocation) obj.readObject();
			//2从注册中心读取服务的请求
			Class implClass = NativeRegistry.get(invocation.getInterfaceName(), new URL("localhost", 8080));
			//3调用服务的反射
			Method method = implClass.getMethod(invocation.getMethodName(), invocation.getParamType());
			String result = (String) method.invoke(implClass.newInstance(), invocation.getParams());
			//4结果返回
			IOUtils.write(result,resp.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

	}
}
